package Year22_Month01.day0127;

public class Solution {
    public boolean isHappy(int n) {
        int slow = n;
        int fast = 0;
        while(fast != slow){
            slow = next(n);
            fast = next(next(n));
        }
        if(slow != 1){
            return false;
        }
        return true;
    }

    public int next(int num){
        int res = 0;
        while(num != 0){
            res += (num % 10) * (num % 10);
            num /= 10;
        }
        return res;
    }


    public int getNext(int n) {
        int totalSum = 0;
        while (n > 0) {
            int d = n % 10;
            n = n / 10;
            totalSum += d * d;
        }
        return totalSum;
    }

    public boolean isHappy2(int n) {
        int slowRunner = n;
        int fastRunner = getNext(n);
        while (fastRunner != 1 && slowRunner != fastRunner) {
            slowRunner = getNext(slowRunner);
            fastRunner = getNext(getNext(fastRunner));
        }
        return fastRunner == 1;
    }

}
